package com.wbhz.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wbhz.entity.Post;
import com.wbhz.entity.Reply;
import com.wbhz.entity.User;
import com.wbhz.service.PostService;
import com.wbhz.service.UserService;

@Controller
public class QAController {
	Logger logger = Logger.getLogger(QAController.class);
	
	@Autowired
	private PostService postService = null;
	
	@Autowired
	private UserService userService = null;
	// 首页
	@RequestMapping("/showAllPost")
	public String showAllPost(@RequestParam(value="currentPage",defaultValue="1",required=false)
			int currentPage, String title, Model model) {
		logger.info("===QAController类的,showAllPost方法===");
		// 获得post列表
		model.addAttribute("pageMsg",postService.selectPostByPage(title, currentPage));
//		System.out.println(" ==test== " + postService.selectPostByPage(title, currentPage));
		// 获得name和tab列表
		model.addAttribute("userMsg",userService.selectUserIdAndName());
		model.addAttribute("tabMsg",postService.selectTabByPost());
		return "post/indexPost";
	}
	// 发帖
	@RequestMapping("/post/showAddUI")
	public String showAddUI(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
		logger.info("===QAController类的,showAddUI方法===");
		request.setAttribute("tabList", postService.selectTab());
//		System.out.println(" ==test== "+request.getAttribute("tabList"));
		return "post/add";
	}
	@RequestMapping("/post/addPost")
	public String addPost(@ModelAttribute Post post, BindingResult bindingResult, HttpServletResponse response, HttpSession httpSession, Model model) throws IOException {
		logger.info("===QAController类的,addPost方法===");
		User user = (User)httpSession.getAttribute("User");
		System.out.println(" ==test== reward: "+post.getPostReward()+"   money: "+user.getUserMoney());
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		if (user.getUserMoney() >= post.getPostReward()) {	// 发帖时扣除发布帖子用户的飞吻值，判断用户飞吻
			userService.updateMoney(user.getUserId(), post.getPostReward());
			postService.insertPost(post);
			out.println("<script>");
			out.println("alert('发帖成功！');");
			out.println("</script>");
		}else {
			out.println("<script>");
			out.println("alert('发帖失败：余额不足！');");
			out.println("</script>");
		}
//		return "user/home";
		return showAllPost(1, null, model);
	}
	/**
	 * 展示帖子详情
	 */
	@RequestMapping("/post/showPostDetail")
	public String showPostDetail(HttpServletRequest request, HttpSession httpSession, Model model, Integer postId,
			@RequestParam(value="currentPage",defaultValue="1",required=false)int currentPage, String byReplyName) {
		logger.info("===QAController类的,showPostDetail方法===");
		request.setAttribute("post", postService.selectPostDetail(postId));
		User user = (User)httpSession.getAttribute("User");
		if (null != byReplyName) { // 回复谁
			request.setAttribute("userName", byReplyName);
			request.setAttribute("byReplyUserId", userService.selectUIdByUName(byReplyName));	// 获得被回复用户id，用于回复
		}else {	// 默认回复楼主
			request.setAttribute("userName", postService.selectUserNameByPid(postId));
			request.setAttribute("byReplyUserId", postService.selectPostUserId(postId));	// 获得楼主用户id，用于回复
		}
		request.setAttribute("replyUserList", userService.selectReplyUList(postId));	// 所有关于这个帖子的回复人的列表
		if (null != user) {	// 游客也可访问帖子详情
			System.out.println(" ==test== ["+user.getUserName()+"]");
			request.setAttribute("isCollect", postService.selectCollect(postId, user.getUserId()));	// 查询该贴是否被该登录用户收藏
			model.addAttribute("isLike", postService.selectLikeByUserId(user.getUserId(), postId));	// 哪一个帖子postId，谁点赞fromLikeUserId，谁被点赞byLikeUserId，谁的回复replyId(一个人可以发多个回复，即可有多个replyId是一个人发的)
			System.out.println(" ==test== isLike: ["+postService.selectLikeByUserId(user.getUserId(), postId)+"]");
			model.addAttribute("isNotLike", postService.selectNotLike(user.getUserId(), postId));
			System.out.println(" ==test== isNotLike: ["+postService.selectNotLike(user.getUserId(), postId)+"]");
		}
//		System.out.println(" ==test== ["+userName.trim()+"]");	// 会多出空格？还未知原因
		model.addAttribute("replyMsg",postService.selectReplyByPage(postId, currentPage));
		model.addAttribute("userReply",userService.selectUserByReply(postId));
		request.setAttribute("isReport", postService.selectReport(postId));	// 查询是否被举报
		postService.addPostBrowse(postId);	// 浏览量+1，真正：数据库+1		怎么实现每个人只算一次浏览量？？
		// 最近热帖 浏览量browse
		// 近期热议 评论量reply
		model.addAttribute("postBrowse",postService.selectPostByCur(1));
		model.addAttribute("postReply",postService.selectPostByCur(2));
		return "forward:detail.jsp";	// "post/detail";
	}
	/**
	 * 置顶帖子与否
	 */
	@RequestMapping("/post/toStickOrNot")
	public String toStickPost(int userId, int postId, String stickOrNot, 
			HttpServletResponse response, HttpServletRequest request, HttpSession httpSession, Model model) throws IOException {
		logger.info("===QAController类的,toStickOrNot方法===");
		System.out.println(" ==test== userId: ["+userId+"]");
		System.out.println(" ==test== postId: ["+postId+"]");
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		if (null != postService.selectVip(userId)) {	// 是vip
			System.out.println(" ==test== stickOrNot: ["+stickOrNot+"]");
			int count = postService.updateStickPost(postId, stickOrNot);
			System.out.println(" ==test== count: ["+count+"]");
			if (stickOrNot.equals("yes") && count == 1) {	// String是引用类型	用.equals() ==不可
				out.println("<script>");
				out.println("alert('置顶成功！');");
				out.println("</script>");
			}else if (stickOrNot.equals("no") && count == 1) {
				out.println("<script>");
				out.println("alert('取消置顶成功！');");
				out.println("</script>");
			}
		}else {
			out.println("<script>");
			out.println("alert('会员才有置顶功能，您还不是会员。');");
			out.println("</script>");
		}
		return showPostDetail(request, httpSession, model, postId, 1, null);
	}
	/**
	 * 回复帖子
	 */
	@RequestMapping("/post/toSubmitReply")
	public String toSubmitReply(@ModelAttribute Reply reply, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request, HttpSession httpSession, Model model) throws IOException {
		logger.info("===QAController类的,toSubmitReply方法===");
		System.out.println(" ==test== reply: ["+reply+"]");
		postService.insertReply(reply);
//		model.addAttribute("replyMsg",postService.selectReplyByPage(reply.getReplyPostId(), currentPage));
//		model.addAttribute("userReply",userService.selectUserByReply());
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		out.println("<script>");
		out.println("alert('回复成功！');");
		out.println("</script>");
		insertMessage(reply.getReplyFromReplyUserId(), reply.getReplyByReplyUserId(), "回复", reply.getReplyContent(), "未阅读");	// 添加信息
		postService.addPostReply(reply.getReplyPostId());	// 回复量+1
		return showPostDetail(request, httpSession, model, reply.getReplyPostId(), 1, null);
	}
	/**
	 * 采纳回复，结贴
	 */
	@RequestMapping("/post/toAdopt")
	public String toAdopt(int replyId, int postId, HttpServletResponse response,HttpServletRequest request, HttpSession httpSession, Model model, int replyFromUserId, int postReward) throws IOException {
		logger.info("===QAController类的,toAdopt方法===");
		postService.updateReplyStatus(replyId);	// 设为最佳答案
		postService.updateStickPost(postId, "no");	// 取消置顶
		postService.updatePostStatus(postId);	// 结贴
		postService.updateUserMoney(replyFromUserId, postReward);	// 结贴，飞吻变更
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		out.println("<script>");
		out.println("alert('采纳回复成功！该帖子已结贴！');");
		out.println("</script>");
		return showPostDetail(request, httpSession, model, postId, 1, null);
	}
	/**
	 * 点赞
	 */
	@RequestMapping("/post/toLikeReply")
	public String toLikeReply(HttpServletRequest request, HttpSession httpSession, Model model, int replyId, int likePostId, int likePostUserId, int likeReplyId, int likeFromUserId, int likeByUserId) {
		logger.info("===QAController类的,toLikeReply方法===");
		int flag = postService.addOrSubReplyLike(likePostId, likePostUserId, likeReplyId, likeFromUserId, likeByUserId);
		postService.updateReplyLike(replyId, flag);	// flag: 1是+1;2是-1
		insertMessage(likeFromUserId, likeByUserId, "点赞", null, "未阅读");	// 添加信息
		return showPostDetail(request, httpSession, model, likePostId, 1, null);
	}
	/**
	 * 举报
	 */
	@RequestMapping("/post/toReport")
	public String toReport(int postId, int postUserId, int reportUserId, String postTitle, HttpServletResponse response,
			HttpServletRequest request, HttpSession httpSession, Model model) throws IOException {
		logger.info("===QAController类的,toReport方法===");
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		if (null != postService.selectReportByUId(postId, reportUserId)) {
			out.println("<script>");
			out.println("alert('你已举报过该贴！请等待审核信息！');");
			out.println("</script>");
		}else {
			postService.insertReport(postId, postUserId, reportUserId, postTitle);
			out.println("<script>");
			out.println("alert('举报成功！请等待审核信息！');");
			out.println("</script>");
		}
		return showPostDetail(request, httpSession, model, postId, 1, null);
	}
	/**
	 * 收藏
	 */
	@RequestMapping("/post/toCollectOrNot")
	public String collectPost(int postId, int postUserId, int userId, HttpServletRequest request, HttpSession httpSession, Model model, HttpServletResponse response) throws IOException {
		logger.info("===QAController类的,toCollectOrNot方法===");
		int flag = postService.addOrSubCollect(postId, postUserId, userId);
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		if (flag == 1) {	// 收藏+1
			request.setAttribute("isCollect", "已收藏");
			out.println("<script>");
			out.println("alert('收藏成功！');");
			out.println("</script>");
		}else if (flag == 2) {	// 取消收藏
			request.setAttribute("isCollect", "未收藏");
			out.println("<script>");
			out.println("alert('取消收藏成功！');");
			out.println("</script>");
		}
		insertMessage(userId, postUserId, "收藏", null, "未阅读");	// 添加信息
		return showPostDetail(request, httpSession, model, postId, 1, null);
	}
	/**
	 * 添加信息(设置内)
	 */
	public void insertMessage(int fromUserId, int byUserId, String msgName, String msgContent, String msgStatus) {
		logger.info("===QAController类的,insertMessage方法===");
		postService.insertMsg(fromUserId, byUserId, msgName, msgContent, msgStatus);
	}
}
